﻿using System;
using System.Windows;
using System.Windows.Media;
using System.Collections.Generic;

namespace Thinktecture.UIAnnotations.Behaviors
{
    public static class VisualTreeHelpers
    {
        public static FrameworkElement GetRootElement(FrameworkElement element)
        {
            var parent = VisualTreeHelper.GetParent(element);
            var lastParent = parent;
            while (parent != null)
            {
                lastParent = parent;
                parent = VisualTreeHelper.GetParent(parent);
            }
            return lastParent as FrameworkElement;
        }

        public static FrameworkElement FindDescendent(FrameworkElement element, string name)
        {
            Stack<FrameworkElement> stack = new Stack<FrameworkElement>();

            for (int i = 0; i < VisualTreeHelper.GetChildrenCount(element); i++)
            {
                stack.Push(VisualTreeHelper.GetChild(element, i) as FrameworkElement);
            }

            while (stack.Count > 0)
            {
                FrameworkElement poppedElement = stack.Pop();
                if (poppedElement != null && String.Equals(poppedElement.Name, name))
                {
                    return poppedElement;
                }
                for (int i = 0; i < VisualTreeHelper.GetChildrenCount(poppedElement); i++)
                {
                    stack.Push(VisualTreeHelper.GetChild(poppedElement, i) as FrameworkElement);
                }
            }

            return null;
        }
    }
}
